Array.prototype.indexOf = function(val) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == val) return i;
    }
    return -1;
};

Array.prototype.remove = function(val) {
    var index = this.indexOf(val);
    if (index > -1) {
        this.splice(index, 1);
    }
};

//弹框时调用
function create(){
    uploader.addButton({
        id: '#picker'
    });
}


var uploader;
var files = [];
/**
 * 初始化上传队列
 */
function uploadInit(){
    //初始化上传控件
    uploader = WebUploader.create({
        // swf文件路径
        swf: 'widget/webuploader/Uploader.swf',
        // 文件接收服务端。
        // server: [[${#request.getContextPath()}]] + '/res/upload',
        server: '/res/upload',
        // 选择文件的按钮。可选。
        // 内部根据当前运行是创建，可能是input元素，也可能是flash.
        pick: '#picker',
        // 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
        resize: false
    });

    //设置入队
    uploader.on("fileQueued", function (file) {
        //预处理文件名称
        var n = file.name;
        if (n.length > 20) {
            n = n.substring(0, 20);
            n += "...";
        }


        //上传列表 - 老版本
        // var fileHtml = "<tr id='tr_" + file.id + "'>" +
        //     "<td>" + n + "</td>" +
        //     "<td id='progress_" + file.id + "'>待上传" +
        //     "<button onclick=\"removeQueue('" + file.id + "')\" type='button' class='close'>" +
        //     "<span>&times;</span>" +
        //     "</button>" +
        //     "</td>" +
        //     "</tr>";

        //上传列表
        var fileHtml = "<li id='tr_" + file.id + "' class='list-group-item'>" + n + " <a id='progress_" + file.id + "' style='float: right'>待上传&nbsp;&nbsp; <button onclick=\"removeQueue('" + file.id + "')\" type='button' class='close'><span>&times;</span></button>  </a></li>";

        //ajax通知后台判断是否上传过该文件
        myajax({
            url: "/res/isupload",
            data: {"filename":file.name},
            success: function(data){
                if(data){
                    $("#progress_" + file.id).html("<font color='green'>云端曲目</font>&nbsp;&nbsp;<button onclick=\"removeQueue('" + file.id + "', '" + file.name +  "')\" type='button' class='close'><span>&times;</span></button>");
                    //从队列中移除
                    uploader.cancelFile(file);
                    files.push(file.name);
                }
            }
        });

        $("#upload_list").append(fileHtml);
    });

    //设置进度条
    uploader.on('uploadProgress', function (file, percentage) {
        var pg = parseInt(percentage * 100) + '%';
        console.log("进度：" + pg);
        $("#progress_" + file.id).html("<font color='green'>" + pg + "</font>");
    });

    //设置成功事件
    uploader.on("uploadSuccess", function (file) {
        $("#progress_" + file.id).html("<font color='green'>上传成功</font>&nbsp;&nbsp;<button onclick=\"removeQueue('" + file.id + "', '" + file.name +  "')\" type='button' class='close'><span>&times;</span></button>");
        files.push(file.name);
    });

    //设置失败事件
    uploader.on("uploadError", function (file) {
        $("#progress_" + file.id).html("<font color='red'>上传失败</font>&nbsp;&nbsp;<button onclick=\"removeQueue('" + file.id + "', '" + file.name +  "')\" type='button' class='close'><span>&times;</span></button>");
    });
}

//初始化上传
$(function () {
    uploadInit();
});

/**
 * 移除队列
 */
function removeQueue(fid, fname) {
    //将文件从列表中移除
    $("#tr_" + fid).remove();
    //将文件从队列中移除
    uploader.removeFile(fid, true);

    //从数组中移除队列
    if(fname){
        for(var i = 0; i < files.length; i++){
            if(files[i] == fname){
                files.splice(i, 1);
            }
        }
    }
}

/**
 * 移除文件数组
 * @param fname
 */
function removeFiles(fid, fname){
    $("#tr_old_" + fid).remove();
    for(var i = 0; i < files.length; i++){
        if(files[i] == fname){
            files.splice(i, 1);
        }
    }
}

/**
 * 开始上传
 */
function start_upload() {
    if (uploader) {
        uploader.upload();
    }
}

/**
 * 重置上传
 */
function resetUpload(){
    //清空上传列表
    $("#upload_list").html("");
    files=[];
    uploader.reset();
}

//回显文件列表
function showUpdate(mp3){
    files = JSON.parse(mp3);
    for(var i = 0; i < files.length; i++){
        // var fileHtml = "<tr id='tr_old_" + i + "'>" +
        //     "<td>" + files[i] + "</td>" +
        //     "<td id='progress_old_" + i + "'><font color='green'>已上传</font>" +
        //     "<button onclick=\"removeFiles('" + i + "','" + files[i] + "')\" type='button' class='close'>" +
        //     "<span>&times;</span>" +
        //     "</button>" +
        //     "</td>" +
        //     "</tr>";

        var fileHtml = "<li id='tr_old_" + i + "' class='list-group-item'>" + files[i] + " <a id='progress_old_" + i + "' style='float: right'><font color='green'>云端曲目</font>&nbsp;&nbsp; <button onclick=\"removeFiles('" + i + "','" + files[i] + "')\" type='button' class='close'><span>&times;</span></button>  </a></li>";
        $("#upload_list").append(fileHtml);
    }
}


//查询云端曲目列表
function show_yun(){
    myajax({
        url: "/res/yunlist",
        success: function(data){
            if(data){
                for(var i = 0; i < data.length; i++){
                    var fileHtml = "<li class='list-group-item' onclick='checkthis(this)'><input type='checkbox' name='yunmusic' onclick='checkstop();' id='" + data[i].id + "' value='" + data[i].name + "'/>" + data[i].name + "</li>";
                    $("#yun_upload_list").append(fileHtml);
                }
            }
        }
    });
}

//复选框选择方法
function checkthis(ele){
    var checkbox = $(ele).find("input[type='checkbox']")[0];
    checkbox.checked = !checkbox.checked;
}

//解决点击透传
function checkstop(e){
    event.stopPropagation();
}

//打开云端曲目弹出框
function open_show_yun(){
    layer.open({
        type: 1 //Page层类型
        ,area: ['300px', '600px']
        ,title: '云端曲目列表',
        offset:'20px',
        btn: ['确定','取消']
        ,shade: 0.6 //遮罩透明度
        ,maxmin: false //允许全屏最小化
        ,anim: 4 //0-6的动画形式，-1不开启
        ,content:$("#yunlistdiv")
        ,yes: function(index, layero){
            //获取选中的云端列表
            var checkeds = $("input[name='yunmusic'][type='checkbox']:checked");
            for(var i = 0; i < checkeds.length; i++){
                var music = checkeds[i].value;
                var id = checkeds[i].id;

                if ($("#tr_yun_" + id).length == 0) {
                    var fileHtml = "<li id='tr_yun_" + id + "' class='list-group-item'>" + music + " <a id='progress_yum_" + id + "' style='float: right'><font color='green'>云端曲目</font>&nbsp;&nbsp; <button onclick=\"removeQueue('yun_" + id + "', '" + music + "')\" type='button' class='close'><span>&times;</span></button>  </a></li>";
                    $("#upload_list").append(fileHtml);

                    //设置到上传列表
                    files.push(music);
                }
            }
            //关闭弹出框
            layer.close(index);
            return true;
        },success: function(layero, index){
            //查询云端列表
            show_yun();
        },
        cancel: function(index, layero){
            $('body').removeAttr('style')
        }
    });
}